package gwtappcontainer.server.apps.security;

import gwtappcontainer.server.apps.APIException;
import gwtappcontainer.shared.apis.APIResponse.Status;
import gwtappcontainer.shared.apps.security.RoleProp;
import gwtappcontainer.shared.apps.security.UserProp;

import com.google.appengine.api.users.User;

public class AccessController {
	
	public static void ensureValidUser(User user) {
		if (null == user)
			throw new APIException(Status.ERROR_LOGIN_REQUIRED, 
					"User not logged in");
		
		if (isSuperUser(user.getEmail()))
			return;
		
		UserProp userProp = UserRepository.getUser(user.getEmail());
		
		if (null == userProp)
			throw new APIException(Status.ERROR_INVALID_USER,
					"User [" + user.getEmail() + "] in invalid");		
		
	}
	
	public static void ensurePrivilege(String login, String privilege) {
		if (null == login)
			throw new APIException(Status.ERROR_LOGIN_REQUIRED, 
					"User not logged in");						
		
		if (isSuperUser(login))
			return;				
		
		UserProp userProp = UserRepository.getUser(login);
		
		if (null == userProp)
			throw new APIException(Status.ERROR_INVALID_USER,
					"User [" + login + "] in invalid");
		
		privilege = privilege.toUpperCase();			
					
		if (userProp.privileges == null)
			throw new APIException(Status.ERROR_INSUFFICIENT_PERMISSION,
					"User [" + login + "] does not have privilege [" + privilege + "]");
		
		if ((userProp.privileges != null) && 
				(userProp.privileges.contains(privilege)))
			return;
		
		for (RoleProp roleProp : userProp.roles) {
			if ((roleProp.privileges != null) && 
					roleProp.privileges.contains(privilege))
				return;
		}
		
		throw new APIException(Status.ERROR_INSUFFICIENT_PERMISSION,
				"User [" + login + "] does not have privilege [" + privilege + "]");	
	}
	
	public static void ensureValidUser(String login) {
		if (null == login)
			throw new APIException(Status.ERROR_LOGIN_REQUIRED, 
					"User not logged in");
		
		if (isSuperUser(login))
			return;
		
		UserProp userProp = UserRepository.getUser(login);
		
		if (null == userProp)
			throw new APIException(Status.ERROR_INVALID_USER,
					"User [" + login + "] in invalid");		
		
	}
	
	public static void ensureLoggedin(User user) {
		if (null == user)
			throw new APIException(Status.ERROR_LOGIN_REQUIRED, 
					"User not logged in");			
	}
	
	public static boolean isSuperUser(String email) {
		return (email.toLowerCase().equals("sathyanarayanant@gmail.com"));
	}
	
	public static boolean hasPrivilege(String login, String privilege) {
		try { 
			ensurePrivilege(login, privilege);
			return true;
		} catch (APIException ex) {
			return false;
		}
	}
}
